package com.zdp.filesync.monitor;

import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import com.zdp.filesync.config.client.FileSyncClientInfo;
import com.zdp.filesync.monitor.config.FileMonitorInfo;
import com.zdp.filesync.notify.service.NotifyClientSyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Future;

/**
 * 统一管理当前程序中的所有线程
 */
@Component
@Slf4j
public class FileMonitorTaskManager {

    private Map<String,FileMonitorTask> tasks = Maps.newHashMap();

    @Autowired
    private NotifyClientSyncService notifyClientSyncService;

    /**
     * 开始 监听
     * @param infos
     */
    public void startMonitor(List<FileMonitorInfo> infos, Integer interval){
        if(CollectionUtils.isEmpty(infos)){
            log.info("传入的文件路径为空，不需要启动文件监听任务");
            return ;
        }
        for(FileMonitorInfo info : infos){
            String path = info.getPath();
            String commentName = info.getCommentName();
            if(!tasks.containsKey(path)){
                FileMonitorTask task = new FileMonitorTask(interval,path,notifyClientSyncService,commentName);
                // 启动任务
                FileMonitorPool.getExecutor().execute(task);
                log.info("启动路径:{}的文件监听任务",path);
                // 缓存任务
                tasks.put(path,task);
            }else{
                log.info("当前路径:{}已经被监听",path);
            }

        }
    }

    /**
     * 取消监听
     * @param paths
     */
    public void cancelMonitorTask(List<String> paths){
        if(CollectionUtils.isEmpty(paths)){
            log.info("传入的需要取消文件监听目录为空");
            return ;
        }
        for(String path : paths){
            FileMonitorTask task = tasks.remove(path);
            if(Objects.nonNull(task)){
                log.info("取消 {} 的文件监听任务",path);
                task.cancel();
            }else{
                log.info("当前路径:{}并没有对应的文件监听任务",path);
            }
        }
    }

    public void setInterval(Integer interval){
        tasks.values().forEach(task -> task.setInterval(interval));
    }

    /**
     * 修改 任务的 commentName
     * @param commentName rsync的模块名称
     */
    public void modifyCommentName(String path ,String commentName){
        FileMonitorTask task = tasks.get(path);
        if(Objects.nonNull(task)){
            task.setCommentName(commentName);
        }
    }

}
